const axios = require("axios");
const fs = require("fs");

const url = "http://localhost:4000",
  bucketName = "bucketName",
  destDirName = "db/__resource__";

const prefixFilter = (prefix) => prefix.substring(0, prefix.length - 1);

const createImage = (bucketName, objectName) => {
  axios
    .post(`${url}/object/presignedGetObject`, {
      bucketName: bucketName,
      objectName: objectName,
    })
    .then((res) => {
      if (res.data.success) {
        axios({
          method: "get",
          url: res.data.data,
          responseType: "arraybuffer",
        }).then((r) => {
          fs.writeFile(
            `./${destDirName}/${objectName}`,
            r.data,
            "binary",
            function (err) {
              if (err) console.error(err);
              console.log(`创建图片${objectName}成功`);
            }
          );
        });
      }
    });
};

const recursive = (bucketName, prefix) => {
  axios
    .post(`${url}/object/listObjects`, {
      bucketName: bucketName,
      prefix: prefix,
      pageNum: -1,
    })
    .then((res) => {
      console.log("获取图片信息", res.data.data);
      if (res.data.success) {
        return res.data.data.lists;
      }
    })
    .then((data) => {
      data?.forEach((d) => {
        if (d.prefix) {
          if (fs.existsSync(`./${destDirName}/${prefixFilter(d.prefix)}`)) {
            recursive(bucketName, d.prefix);
          } else {
            fs.promises
              .mkdir(`./${destDirName}/${prefixFilter(d.prefix)}`)
              .then(() => {
                recursive(bucketName, d.prefix);
              })
              .catch((err) => console.error(err));
          }
        } else {
          if (/\.(png|svg|jepg|jpg|gif|mp4|mp3|avi|flv)$/.test(d.name)) {
            console.log("d.name", d.name);
            createImage(bucketName, d.name);
          }
        }
      });
    });
};

recursive(bucketName, "");